package com.sunzhe.cms.web;

import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.ParamUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.CmsComment;
import com.ibeetl.cms.service.CmsCatalogService;
import com.ibeetl.cms.service.CmsCommentService;
import com.ibeetl.cms.web.query.CmsCommentQuery;
import com.ibeetl.member.entity.Member;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 首页 接口
 */
@Controller
public class CmsCommentController {

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "cms/comment";
    @Autowired
	CmsCatalogService catalogService;
	@Autowired
	Environment env;
	@Autowired
	CorePlatformService platformService;
	@Autowired
	private StringRedisTemplate redisClient ;
	@Autowired
	private CmsCommentService commentService;

	@PostMapping(MODEL + "/add.json")
	@ResponseBody
	public JsonResult<CmsComment> commentAdd(@Validated(ValidateConfig.ADD.class)  CmsComment cmsComment, HttpServletRequest request) {
		return this.commentSave(cmsComment,request);
	}

	@PostMapping(MODEL + "/update.json")
	@ResponseBody
	public JsonResult<CmsComment> commentUpdate(@Validated(ValidateConfig.UPDATE.class)  CmsComment cmsComment, HttpServletRequest request) {
		return this.commentSave(cmsComment,request);
	}

	public JsonResult<CmsComment> commentSave(CmsComment cmsComment, HttpServletRequest request) {
		CmsComment cmsCommentDb = commentService.queryById(cmsComment.getId());

		if (cmsCommentDb == null) {
			cmsCommentDb = new CmsComment();
			cmsCommentDb.setCreateTime(new Date());
		}
		cmsCommentDb.setUpdateTime(new Date());
		cmsCommentDb = ParamUtil.initParameterObj(request, cmsCommentDb);
		Member member = platformService.getCurrentMemberOnly();
		if (member != null) cmsCommentDb.setMemberId(member.getId());

		int count = commentService.upsert(cmsCommentDb);
		if (count > 0) {
			this.commentService.clearCommentListCache();
			return new JsonResult().success(cmsCommentDb);
		} else {
			return JsonResult.failMessage("保存失败");
		}
	}

	/* ajax json */
	@PostMapping(MODEL + "/list.json")
	@ResponseBody
	public JsonResult<PageQuery> list(CmsCommentQuery condition)
	{
		PageQuery page = commentService.queryByCondition(condition);
		JsonResult result = JsonResult.success(page);
		return result;
	}
}
